<script setup>
import { reactive, ref } from 'vue';
import { LOGIN } from '@/router/routeMap'

defineProps({
  isLoadingOfRegister: Boolean
})
const emit = defineEmits(['clickRegister'])

const title = ref('立即注册')
const formData = reactive({
  username: '',
  password: '',
  confirmPassword: ''
})
const formRef = ref()
const validatePassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== formData.password) {
    callback(new Error("两次密码不匹配!"))
  } else {
    callback()
  }
}
const rules = reactive({
  username: { required: true, type: 'string', trigger: 'blur', message: '用户名不能为空' },
  password: { required: true, type: 'string', trigger: 'blur', message: '密码不能为空' },
  confirmPassword: { validator: validatePassword, trigger: 'blur' }
})

const onClickRegister = () => {
  if (!formRef.value) return
  formRef.value.validate((valid) => {
    if (valid) {
      emit('clickRegister', { username: formData.username, password: formData.password })
    } else {
      return false
    }
  })
}
</script>

<template>
  <el-form
    class="form-container"
    label-width="100px"
    :model="formData"
    :rules="rules"
    ref="formRef"
  >
    <h1 class="caption">{{ title }}</h1>
    <el-form-item label="用户名：" prop="username">
      <el-input v-model="formData.username" />
    </el-form-item>
    <el-form-item label="密码：" prop="password">
      <el-input type="password" v-model="formData.password" />
    </el-form-item>
    <el-form-item label="确认密码：" prop="confirmPassword">
      <el-input type="password" v-model="formData.confirmPassword" />
    </el-form-item>
    <el-form-item>
      <el-button
        class="button"
        type="primary"
        @click="onClickRegister"
        :loading="isLoadingOfRegister"
      >注册</el-button>
    </el-form-item>
    <el-form-item>
      <el-row justify="space-between" class="path-link">
        <router-link :to="LOGIN">已有帐号，立即登录</router-link>
      </el-row>
    </el-form-item>
  </el-form>
</template>

<style lang="sass" scoped>

.caption
  margin-bottom: 30px
  text-align: center

.form-container
  width: 30vw
  min-width: 400px
  margin: auto
  margin-top: 10vh
  .button
    width: 100%

.path-link
  a
    font-size: 12px
    text-decoration: none
</style>